<template lang="pug">
data-page(
  v-bind="pageParams"
)
  mt-table(
    v-bind="tableProps"
  )
  edit-form(
    v-bind="editFormProps"
  )
  
  addBaseProject(v-model="baseProjectShow" :selectEquipment="props.selectEquipment" :currentSpecimen="props.currentSpecimen")
</template>

<script setup lang="ts">
import {
  type IAction,
  type DataPageProps,
  type Action,
  type TableProps,
  useNotify,
  type EditFormProps,
  type FormItemProps,
} from "@scmt/common-components";
import { useQuery } from "@scmt/common-hooks";
import { type QueryPagination, useApi } from "@scmt/core-api";
import { type QualityControlEntity } from "@scmt/api-lis-quality-control";
import {
  type BaseProjectEntity,
  type BaseProjectQueryParams,
} from "@scmt/api-lis-base-project";
import addBaseProject from "./addBaseProject.vue";
import { type EquipmentEntity } from "@scmt/api-lis-equipment";

const $api = useApi();
const $notify = useNotify();
const queryPramas = reactive<BaseProjectQueryParams>({
  pageNum: 1,
  pageSize: 20,
});
const editingObj = ref<null | BaseProjectEntity>(null);
const baseProjectShow = ref(false);

//添加 Props属性
const props = defineProps({
  selectEquipment: {
    type: Object as PropType<QualityControlEntity>,
    default: () => {},
  },
  currentSpecimen: {
    type: Object as PropType<EquipmentEntity>,
    default: () => {},
  },
});

const { query, data, loadingMap } = useQuery({
  tableData: (q: any) => {
    let params = Object.assign(
      { qualityControlId: props.selectEquipment?.value?.id },
      queryPramas,
      q
    );
    if (!props.selectEquipment || !props.selectEquipment.id) {
      $notify.warning("请先选择标本质控字典");
      //没有选择设备的话 deviceId传一个不会有的值
      params = Object.assign({ qualityControlId: "testtt" }, queryPramas, q);
    } else {
      params = Object.assign(
        {
          qualityControlId: props.selectEquipment?.id,
        },
        queryPramas,
        q
      );
    }
    return $api.lis.baseProject.getRelatedQualityControlIdProjectListByPage(
      params
    );
  },
  save: (model: BaseProjectEntity) => {
    return $api.lis.baseProject.save(model).then(() => {
      $notify.success("保存成功");
      editingObj.value = null;
      query("tableData", {
        pageSize: 20,
      });
    });
  },
  destroy: (ids: string) => {
    return $api.lis.portfolioProject.destroy(ids).then(() => {
      $notify.success("删除成功");

      query("tableData", {
        pageSize: 1,
      });
    });
  },
});

const pageParams = computed<DataPageProps>(() => {
  const headerActions: Action[] = [
    {
      label: "批量关联",
      event: "completeCollection",
      type: "primary",
    },
  ];

  const dataPageProps: DataPageProps = {
    loading: loadingMap.tableData,
    queryModel: queryPramas,
    actions: headerActions,
    onQuery: () => query("tableData"),
    onAct: onPageActions,
    columns: 2,
    alignAction: "left",
  };

  return dataPageProps;
});

const tableProps = computed(() => {
  const { tableData } = toRefs(data);

  const tableProps: TableProps = {
    loading: loadingMap.tableData,
    data: tableData.value?.items,
    pagination: tableData.value?.pagination,
    columns: [
      {
        prop: "shortName",
        label: "检验项目编码",
      },
      {
        prop: "name",
        label: "检验项目名称",
      },
      {
        prop: "method",
        label: "方法",
      },
      {
        prop: "reagent",
        label: "试剂",
      },
      {
        prop: "calibration",
        label: "校准",
      },
      {
        prop: "allowTotalError",
        label: "允许总误差",
      },
      {
        prop: "nonPrecision",
        label: "不精密度",
      },
      {
        prop: "inaccuracy",
        label: "不准确度",
      },
      {
        label: "操作",
        actions: [
          {
            label: "编辑",
            event: "edit",
            type: "primary",
          },
          {
            label: "取消关联",
            event: "cancel",
            type: "primary",
          },
        ],
      },
    ],
    onAct: onPageActions,
    onPaginate: (pagination: QueryPagination) => query("tableData", pagination),
    highlightCurrentRow: true,
  };
  return tableProps;
});

const editFormProps = computed<EditFormProps>(() => {
  const formItems: FormItemProps[] = [
    {
      prop: "name",
      label: "检验项目名称",
      required: false,
      disabled: true,
    },
    {
      prop: "method",
      label: "方法",
      required: false,
    },
    {
      prop: "reagent",
      label: "试剂",
      required: false,
    },
    {
      prop: "calibration",
      label: "校准",
      required: false,
    },
    {
      prop: "allowTotalError",
      label: "允许误差值",
      required: false,
    },
    {
      prop: "nonPrecision",
      label: "不精密度",
      required: false,
    },
    {
      prop: "inaccuracy",
      label: "不准确度",
      required: false,
    },
  ];

  const editProps: EditFormProps = {
    model: editingObj.value,
    items: formItems,
    columns: 2,
    size: "middle",
    onClose: () => {
      editingObj.value = null;
    },
    onCancel: () => {
      editingObj.value = null;
    },
    onValidate: (model) => {
      query("save", model);
    },
  };

  return editProps;
});

const onPageActions = (action: IAction, model?: any) => {
  switch (action.event) {
    case "add":
    case "edit":
      editingObj.value = $api.lis.baseProject.$$createEntity(model);
      break;
    case "destroy":
      query("destroy", model ? model.id : "");
      break;
    case "completeCollection":
      baseProjectShow.value = true;
      break;
    case "cancel":
      if (!model) {
        $notify.error("请选择需要取消关联的检验项目");
        return;
      }
      const projectIdData = [].concat(model).map((item) => {
        return item.id;
      });
      $api.lis.qualityBase
        .cancelDeviceRelatedPortfolioProjects(
          props.selectEquipment?.id ?? "",
          projectIdData
        )
        .then(() => {
          $notify.success("取消关联成功");
          query("tableData");
        })
        .catch((error) => {
          $notify.error(error.message);
        });
      break;
  }
};

watch(
  () => props.selectEquipment,
  (item) => {
    if (item && item.id) {
      query("tableData");
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less" scoped></style>
